<template>
  <div class="personBox">
    <el-card>
      <div slot="header">个人中心</div>
      <div class="card-body">
        <p>账号：{{ userInfo.account }}</p>
        <el-divider></el-divider>
        <p>用户组：{{ userInfo.userGroup }}</p>
        <el-divider></el-divider>
        <p>创建时间：{{ userInfo.ctime | handleTime }}</p>
        <el-divider></el-divider>
        <p>
          头像：
          <el-upload
            class="avatar-uploader"
            action="http://sell.h5.itsource.cn:8087/users/avatar_upload"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
          >
            <img v-if="userInfo.imgUrl" :src="userInfo.imgUrl" class="avatar" />
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </p>
      </div>
    </el-card>
  </div>
</template>

<script>
import { mapState } from "vuex";
import { $_user_avataredit } from "@/api/user";
export default {
  data() {
    return {
      imageUrl: "",
    };
  },
  computed: {
    ...mapState(["userInfo"]),
  },
  methods: {
    // 上传成功执行的函数
    handleAvatarSuccess(res) {
      // 先拿到上传的图片地址
      let { imgUrl } = res;

      // 更新vuex中userInfo
      this.$store.commit("SET_USERINFO", { ...this.userInfo, imgUrl });

      // 同时发送请求通知后端修改用户头像
      $_user_avataredit({
        imgUrl,
      }).then((res) => {
        console.log(55, res);
        if (res.data.code == 0) {
          this.$message({
            type: "success",
            message: res.data.msg,
          });
        } else {
          this.$message({
            type: "error",
            message: res.data.msg,
          });
        }
      });
    },
    // 上传前执行的函数
    beforeAvatarUpload(file) {
      let typeArr = ["image/jpeg", "image/png", "image/gif"];
      const isTypes = typeArr.includes(file.type);
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isTypes) {
        this.$message.error("上传头像图片只能是 JPG 格式!");
      }
      if (!isLt2M) {
        this.$message.error("上传头像图片大小不能超过 2MB!");
      }
      return isTypes && isLt2M;
    },
  },
};
</script>

<style lang="less" scoped>
/deep/.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
/deep/.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
/deep/.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
/deep/.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>